﻿using System;
using System.Text;
using System.Data;
using System.Collections;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.RM.DataAccess;
using WP.RM.DataEntity;

namespace WP.RM.BusinessRule
{
    public class RMProductBOMHdrBRL : RuleBase
    {

        #region BOM Detail

        public bool InitProductBOMFromCategorySet(DBAccess dbcon, string strProductFItemID, string strCategoryID, string strSetID, string strTechnicsName)
        {
            string strSQL ="";
            string strProductName = DataFunctions.GetFieldValue(dbcon, "rmProduct", "ProductName", "ProductFItemID='" + strProductFItemID + "'");
            #region 检查 【类别系列BOM】是不是已被审核
            strSQL =" select * from rmCategorySetBOMHdr A where A.Approval=1";
            strSQL += " and A.CategoryID='{0}' and A.SetID='{1}'  ";
            strSQL = string.Format(strSQL, strCategoryID, strSetID);
            DataRow drCheck = dbcon.GetDataFirstRow(strSQL);
            if (drCheck == null)
            {
                MessageBox.Show("没有被审核 【类别系列BOM】", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true ;
            }
            #endregion
            int intRow = 1;
            RMProductBOMHdrDAL rmBOM = new RMProductBOMHdrDAL();
            strSQL  =" select A.* from rmCategorySetBOMDetail A  ";
            strSQL += " inner join rmCategorySetBOMHdr B on A.CategoryID=B.CategoryID and A.SetID=B.SetID and B.Approval=1";
            strSQL += " where A.CategoryID='{0}' and A.SetID='{1}'  order by A.RowSeqNo";
            strSQL = string.Format(strSQL, strCategoryID, strSetID);
            DataTable dtOld = dbcon.GetDataTable(strSQL);            
            foreach (DataRow dr in dtOld.Rows)
            {
                DataRow drBOM = dbcon.GetDataSet("select * from rmProductBOMDetail").Tables[0].NewRow();
                
                drBOM["SeqNo"] = intRow ;
                drBOM["RowSeqNo"] = intRow;
                drBOM["WKID"] = dr["WKID"].ToString().TrimEnd();
                drBOM["WKName"] = DataFunctions.GetFieldValue(dbcon, "rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='"+ dr["WKID"] +"'") ;
                drBOM["ProductFItemID"] = strProductFItemID;
                drBOM["ProductName"] = strProductName;
                drBOM["TechnicsName"] = strTechnicsName;
                drBOM["CategoryID"] = dr["CategoryID"].ToString().TrimEnd();
                drBOM["CategoryName"] = DataFunctions.GetFieldValue(dbcon, "rmCategory", "CategoryName", " CategoryID='" + dr["CategoryID"] + "'");
                drBOM["SetID"] = CvtFunc.ToString(dr["SetID"]);
                drBOM["SetName"] = DataFunctions.GetFieldValue(dbcon, "rmSet", "SetName", " SetID='" + dr["SetID"] + "'");
                drBOM["FItemID"] = CvtFunc.ToString(dr["FItemID"]);
                drBOM["ItemNo"] =  DataFunctions.GetFieldValue (dbcon,"imInvMaster","ItemNo","FItemID='"+ dr["FItemID"] +"'") ;
                drBOM["ItemName"] = DataFunctions.GetFieldValue(dbcon, "imInvMaster", "ItemName", "FItemID='" + dr["FItemID"] + "'");
                drBOM["SupNo"] = CvtFunc.ToString(dr["SupNo"]);
                drBOM["SupName"] = CvtFunc.ToString(dr["SupName"]);
                drBOM["LabourCost"] = BaseFunctions.FormatNumeric(dr["LabourCost"], "Ns.4");
                drBOM["Price"] = BaseFunctions.FormatNumeric(dr["Price"], "Ns.3");
                drBOM["PriceUnit"] = CvtFunc.ToString(dr["PriceUnit"]);
                drBOM["Qty"] = BaseFunctions.FormatNumeric(dr["Qty"], "Ns.8");
                drBOM["QtyWastage"] = BaseFunctions.FormatNumeric(dr["QtyWastage"], "Ns.2");
                drBOM["WastageRate"] = BaseFunctions.FormatNumeric(dr["WastageRate"], "Ns.2");
                drBOM["TotalCost"] = BaseFunctions.FormatNumeric(dr["TotalCost"], "Ns.2");
                drBOM["DetailCost"] = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                drBOM["IsKeyWK"] = dr["IsKeyWK"].ToString();
                drBOM["IsInputWK"] = dr["IsInputWK"].ToString();
                if (!rmBOM.UpdateBOMDetail(dbcon, drBOM))
                {
                    return false;
                }

                // Init  rmWKProductFormula from rmWKFormula
                strSQL = "select * from rmWKFormula where BOMRecID='" + CvtFunc.ToString(dr["RecID"]) + "'";
                DataTable dtFormula = dbcon.GetDataTable(strSQL);
                foreach (DataRow drFormula in dtFormula.Rows)
                {
                    strSQL = @"Insert Into rmWKProductFormula (BOMRecID,ProductName,WKFormula)
                              VALUES ('{0}','{1}','{2}')";
                    strSQL = string.Format(strSQL, drBOM["RecID"], drBOM["ProductName"], drFormula["WKFormula"]);
                    dbcon.ExecuteSql(strSQL);
                }
                intRow++;
                rmBOM.UpdateBOMDetail(dbcon, drBOM); 
            }
            intRow = 1;
            strSQL = "select A.* from rmCategorySetBOMLabourCost A where A.CategoryID='{0}' and A.SetID='{1}' order by a.RowSeqNo ";
            strSQL = string.Format(strSQL, strCategoryID, strSetID);
            dtOld = dbcon.GetDataTable(strSQL);
            foreach (DataRow dr in dtOld.Rows)
            {
                DataRow drBOM = dbcon.GetDataSet("select * from rmProductBOMLabourCost").Tables[0].NewRow();
                
                drBOM["SeqNo"] =intRow ;
                drBOM["RowSeqNo"] = intRow;
                drBOM["WKID"] = dr["WKID"].ToString(); 
                drBOM["WKName"] = dr["WKName"].ToString().TrimEnd();
                drBOM["WKOutName"] = dr["WKOutName"].ToString().TrimEnd();
                drBOM["WKPriceType"] = CvtFunc.ToString(dr["WKPriceType"]);
                drBOM["ProductFItemID"] = strProductFItemID;
                drBOM["ProductName"] = strProductName;
                drBOM["TechnicsName"] = strTechnicsName;
                drBOM["CategoryID"] = strCategoryID;
                drBOM["CategoryName"] = DataFunctions.GetFieldValue(dbcon, "rmCategory", "CategoryName", " CategoryID='" + dr["CategoryID"] + "'");
                drBOM["SetID"] = CvtFunc.ToString(dr["SetID"]);
                drBOM["SetName"] = DataFunctions.GetFieldValue(dbcon, "rmSet", "SetName", " SetID='" + dr["SetID"] + "'");
                drBOM["IsKeyWK"] = CvtFunc.ToBoolean(dr["IsKeyWK"]);
                drBOM["FItemID"] = CvtFunc.ToString(dr["FItemID"]);
                drBOM["ItemNo"] = DataFunctions.GetFieldValue(dbcon, "imInvMaster", "ItemNo", "FItemID='" + dr["FItemID"] + "'");
                //drBOM["ItemName"] = DataFunctions.GetFieldValue(dbcon, "imInvMaster", "ItemName", "FItemID='" + dr["FItemID"] + "'");
                drBOM["CalUnit"] = CvtFunc.ToString(dr["CalUnit"]);
                drBOM["CutType"] = CvtFunc.ToString(dr["CutType"]);
                drBOM["TotalQty"] = BaseFunctions.FormatNumeric(dr["TotalQty"], "Ns.4");
                drBOM["StandardQty"] = BaseFunctions.FormatNumeric(dr["StandardQty"], "Ns.3");
                drBOM["SpendHours"] = CvtFunc.ToString(dr["SpendHours"]);
                drBOM["StandardWage"] = BaseFunctions.FormatNumeric(dr["StandardWage"], "Ns.2");
                drBOM["StandardWage26"] = BaseFunctions.FormatNumeric(dr["StandardWage26"], "Ns.2");
                drBOM["UnitCost"] = BaseFunctions.FormatNumeric(dr["UnitCost"], "Ns.2");
                drBOM["Remark"] = CvtFunc.ToString(dr["Remark"]);
                string strWKPriceType = CvtFunc.ToString(drBOM["WKPriceType"]);
                strSQL = "select * from [imCategoryWKWorkCost] where CategoryID='{0}' and WKProductID='{1}' and WKPriceType='{2}'";
                strSQL = string.Format(strSQL, strCategoryID, CvtFunc.ToString(drBOM["WKID"]), strWKPriceType);
                dbcon = new DBAccess(false, false);
                DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                if (drRow != null)
                {
                    drBOM["CalUnit"] = CvtFunc.ToString(drRow["STDQtyUnit"]);
                    drBOM["StandardQty"] = BaseFunctions.FormatNumeric(drRow["WKSTDQty"], "Ns.2");
                    drBOM["StandardWage"] = BaseFunctions.FormatNumeric(drRow["WKSalary"], "Ns.2");
                    drBOM["StandardWage26"] = BaseFunctions.FormatNumeric(drRow["WKSTDSalary"], "Ns.2");
                    drBOM["UnitCost"] = BaseFunctions.FormatNumeric(drRow["WKUnitCost"], "Ns.6");
                    drBOM["WorkCost"] = CvtFunc.ToString(drRow["WorkCostRate"]);
                }
                if (!rmBOM.UpdateLabourCostDetail(dbcon, drBOM))
                {
                    return false;
                }
                // Init  rmWKProductFormula from rmWKFormula
                strSQL = "select * from rmWKFormulaOtherCategorySetBOM where BOMRecID='" + CvtFunc.ToString(dr["RecID"]) + "'";
                DataTable dtFormula = dbcon.GetDataTable(strSQL);
                foreach (DataRow drFormula in dtFormula.Rows)
                {
                    strSQL = @"Insert Into rmWKFormulaOtherProductBOM (BOMRecID,ProductName,WKFormula)
                              VALUES ('{0}','{1}','{2}')";
                    strSQL = string.Format(strSQL, drBOM["RecID"], drBOM["ProductName"], drFormula["WKFormula"]);
                    dbcon.ExecuteSql(strSQL);
                }
                rmBOM.UpdateLabourCostDetail(dbcon, drBOM); 
                intRow++;
            }
            return true;
        }

        public bool UpdateDetailValid(DBAccess dbcon, DataRow drBOM)
        {
            RMProductBOMHdrDAL rmBOM = new RMProductBOMHdrDAL();
            if (CheckDetailValid(dbcon, drBOM))
            {
                return rmBOM.UpdateBOMDetail(dbcon, drBOM);
            }
            else
                return false;
        }

        public bool UpdateDetailValid_LabourCost(DBAccess dbcon, DataRow drBOM)
        {
            RMProductBOMHdrDAL rmBOM = new RMProductBOMHdrDAL();
            if (CheckDetailValid_LabourCost(dbcon, drBOM))
            {
                return rmBOM.UpdateLabourCostDetail(dbcon, drBOM);
            }
            else
                return false;
        }

        public bool CheckDetailValid(DBAccess dbcon, DataRow drBOM)
        {
            return true;
        }

        public bool CheckDetailValid_LabourCost(DBAccess dbcon, DataRow drBOM)
        {
            return true;
        }

        public bool DeleteDetailValid(DBAccess dbcon, string strRecID)
        {
            return true;
        }
        public bool DeleteDetailValid_LabourCost(DBAccess dbcon, string strRecID)
        {
            return true;
        }
        #endregion


        #region Insert Valid
        public bool InsertValid(DBAccess dBAccess, RMProductBOMHdrDEL rmProductDEL)
        {
            bool bReturn = true;
            string strErrPrompt = string.Empty;
            SysVar.ErrorMessage.Clear();

            string strSetName = rmProductDEL.Tables[RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR].Rows[0][RMProductBOMHdrDEL.SetName].ToString()    ;
            string strCategoryName = rmProductDEL.Tables[RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR ].Rows[0][RMProductBOMHdrDEL.CategoryName].ToString();
            string strProductName = rmProductDEL.Tables[RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR].Rows[0][RMProductBOMHdrDEL.ProductName].ToString();
            string strTechnicsName = rmProductDEL.Tables[RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR].Rows[0][RMProductBOMHdrDEL.TechnicsName].ToString();

            string strSQL = "select * from " + RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR + " where  ProductName='" + strProductName + "' and SetName='" + strSetName + "' and CategoryName='" + strCategoryName + "' and TechnicsName='" + strTechnicsName + "' ";
            DataRow drRow = dBAccess.GetDataFirstRow(strSQL);
            if ( drRow !=null )
            {
                SysVar.ErrorMessage.Add("不能添加相同的记录");
                return false;
            }

            DataView dvwCheck = dBAccess.GetDataTable("select * from mnamedict where NeedCheck=1 and tablename='" + RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR + "'").DefaultView;
            foreach (DataRowView drw in dvwCheck)
            {
                if (!FieldCheck(dBAccess, rmProductDEL.Tables[RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR].Rows[0], drw["FieldName"].ToString(), ref strErrPrompt, FormStatus.AddNew))
                {
                    bReturn = false;
                    if (SysVar.ErrorMessage.Count == 0)
                    {
                        SysVar.ErrorMessage.Add(new ErrInfo(strErrPrompt, drw["FieldName"].ToString()));
                    }
                    break;
                }
            }

            
            return bReturn;
        }
        #endregion

        #region Update Valid
        public bool UpdateValid(DBAccess dBAccess, RMProductBOMHdrDEL RMProductDEL)
        {
            bool bReturn = true;
            string strErrPrompt = string.Empty;
            SysVar.ErrorMessage.Clear();

            if (IsExistedAndNotChanged(dBAccess, RMProductDEL.Tables[RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR]))
            {
                DataView dvwCheck = dBAccess.GetDataTable("select * from mnamedict where NeedCheck=1 and tablename='" + RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR + "'").DefaultView;
                foreach (DataRowView drw in dvwCheck)
                {
                    if (!FieldCheck(dBAccess, RMProductDEL.Tables[RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR].Rows[0], drw["FieldName"].ToString(), ref strErrPrompt, FormStatus.Update))
                    {
                        bReturn = false;
                        if (SysVar.ErrorMessage.Count == 0)
                        {
                            SysVar.ErrorMessage.Add(new ErrInfo(strErrPrompt, drw["FieldName"].ToString()));
                        }
                        break;
                    }
                }
            }
            else
            {
                bReturn = false;
            }
            return bReturn;
        }
        #endregion

        #region Delete Valid
        public bool DeleteValid(DBAccess dBAccess, string strRecId, byte[] btOldRecStamp)
        {
            SysVar.ErrorMessage.Clear();

            if (!base.IsExistedAndNotChanged(dBAccess, "rmProductBOMHdr", strRecId, btOldRecStamp))
                return false;
            if (MsgBoxEx.Show(Msg.Select("您确定要删除此记录?", DataFunctions.GetMsg("SureToDeleteThisRecord")), SysVar.ConfirmTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region Field Check
        public bool FieldCheck(DBAccess dbcon, DataRow dr, string strFieldName, ref string strErrPrompt, FormStatus formStatus)
        {
            strErrPrompt = string.Empty;
            if (strFieldName == null) return true;

            bool blnExistsField = false;
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                if (dr.Table.Columns[i].Caption.ToUpper().Trim() == strFieldName.Trim().ToUpper())
                {
                    blnExistsField = true;
                    break;
                }
            }
            if (!blnExistsField) return true;
            string strFieldValue = CvtFunc.ToString(dr[strFieldName.Trim()]);

            switch (strFieldName.ToUpper().Trim())
            {

                default:
                    return RuleBase.FieldValueCheckOne(dbcon, strFieldValue, RMProductBOMHdrDEL.TABLENAME_RMProductBOMHDR, strFieldName, ref strErrPrompt);
            }
        }
        #endregion
        
    }
}
